package com.example.compents.iec.iec104.server.master;



import com.example.compents.iec.iec104.common.NettyChannelMng;
import com.example.compents.iec.iec104.config.Iec104Config;
import com.example.compents.iec.iec104.server.Iec104Master;
import com.example.compents.iec.iec104.server.handler.DataHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;
import org.springframework.scheduling.annotation.Async;

import java.net.InetAddress;

/**
 * 
 * @ClassName:  Iec104TcpClientMaster   
 * @Description: 104 TCP 客户端 主机
 * @author: YDL
 * @date:
 */

public class Iec104TcpClientMaster implements Iec104Master {

	private int port;
	private String host;
	private DataHandler dataHandler;
	private Iec104Config iec104Config;

	public Iec104TcpClientMaster(String host, int port) {
		this.port = port;
		this.host = host;
	}

	@Override
	@Async
	public void run() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();

	    Bootstrap bs = new Bootstrap();
	    bs.group(bossGroup)
	      .channel(NioSocketChannel.class)
	      .option(ChannelOption.SO_KEEPALIVE, true)
	      .handler(new Iec104ClientInitializer().setDataHandler(dataHandler).setIec104Config(iec104Config));
	    // 客户端开启
	    Channel channel  = bs.connect(host, port).sync().channel();
		System.out.println("开启客户端");
		String ip = InetAddress.getLocalHost().getHostAddress();
		NettyChannelMng.addActiveDeviceChannel(ip, channel);
//	    channel.closeFuture().sync();//阻塞主线程
		channel.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				bossGroup.shutdownGracefully();
			}
		});

	}

	@Override
	public Iec104Master setDataHandler(DataHandler dataHandler) {
		this.dataHandler = dataHandler;
		return this;
	}

	@Override
	public Iec104Master setConfig(Iec104Config iec104Config) {
		this.iec104Config = iec104Config;
		return this;
	}
}
